package com.itheima.filter;
import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
@Slf4j
public class EmployeeFilter implements Filter {
    //路径匹配器，匹配路径还支持通配符写法
public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
      HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求到的路径，本次请求的URI
        String requestURI = request.getRequestURI();
//定义不需要拦截的路径
        String [] us = new String[]{
               "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/common/**",
                "/user/sendMsg",
                "/user/login",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
      /*  log.info("拦截到请求：{}",requestURI);*/
        //判断本次请求是否需要处理
        boolean check = check(us, requestURI);
        //判断，如果不需要处理则直接放行
        if (check){
            filterChain.doFilter(request,response);
            return;
        }
        //判断登录状态，如果已经登陆，则放行
        if (request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录，用户Id为：{}",request.getSession().getAttribute("employee"));
            //设置当前用户Id
            Long employee = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrenId(employee);
            filterChain.doFilter(request,response);
            return;
        }
        //判断登录状态，如果已经登陆，则放行
        if (request.getSession().getAttribute("user")!=null){
            log.info("用户已登录，用户Id为：{}",request.getSession().getAttribute("user"));
            //设置当前用户Id
            Long user = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrenId(user);
            filterChain.doFilter(request,response);
            return;
        }
        //如果未登录则返回未登录结果，通过输出流的方式
        //NOTLOGIN是前端的未登录中的判断条件，
        // 通过输出流给返回这串字母，
        // 前端接受到这串字母就代表没有登录，就会返回到登录界面
response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
return;
    }
/*
* 路径匹配，判断是否需要放行
* */
    public boolean check(String[] us,String requestURI){
        for (String as: us) {
            //match:匹配的意思
            boolean ma = PATH_MATCHER.match(as, requestURI);
            //如果匹配则返回true
            if (ma){
                return true;
            }
        }
        return false;
    }
}
